package com.fulihui.information.core.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fulihui.information.common.config.AppConst;
import com.fulihui.information.core.db.ContentTopDB;
import com.fulihui.information.dto.ContentListItemDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import static org.near.toolkit.common.StringUtil.isBlank;

/**
 * @author Created by Willard Hu on 2016/12/29.
 */
@Component("redisContentTopDB")
public class RedisContentTopDB implements ContentTopDB {
    /**
     * 资讯置顶记录 Redis Key
     */
    private static final String CONTENT_TOP_KEY = "INFORMATION:CONTENT_TOP";

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private AppConst  appConst;

    /**
     * @see ContentTopDB#setTop(String, ContentListItemDTO)
     */
    @Override
    public void setTop(String categoryCode, ContentListItemDTO item) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hset(CONTENT_TOP_KEY, categoryCode, JSON.toJSONString(item));
            jedis.expire(CONTENT_TOP_KEY, appConst.getContentTopExpireSec());
        }
    }

    /**
     * @see ContentTopDB#getTop(String)
     */
    @Override
    public ContentListItemDTO getTop(String categoryCode) {
        try (Jedis jedis = jedisPool.getResource()) {
            String value = jedis.hget(CONTENT_TOP_KEY, categoryCode);
            if (isBlank(value)) {
                return null;
            }
            return JSONObject.parseObject(value, ContentListItemDTO.class);
        }
    }

    /**
     * @see ContentTopDB#remove(String)
     */
    @Override
    public boolean remove(String categoryCode) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hdel(CONTENT_TOP_KEY, categoryCode) > 0;
        }

    }
}
